package com.jolink.omiis.wechat.mongo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongodbManager {

	private static Logger logger = LoggerFactory.getLogger(MongodbManager.class);
	private static MongodbManager instance = null;
	private static String MODE_1 = "single";
	private static String MODE_2 = "replSet";

	private MongodbManager() {
		if (instance == null) {
			try {
				Properties mongodbProp = ConfigUtils.loadConfig(new File(IPreferenceKeys.MONGODB_CONFIG_PATH));
				logger.info("Mongodb配置信息：" + mongodbProp);
				String mode = mongodbProp.getProperty("mode");
				String databaseName = mongodbProp.getProperty("databaseName",
						IPreferenceKeys.MONGODB_DEFAULT_DATABASENAME);
				if (MODE_1.equals(mode)) {
					String host = mongodbProp.getProperty("host", IPreferenceKeys.MONGODB_DEFAULT_HOST);
					String port = mongodbProp.getProperty("port", IPreferenceKeys.MONGODB_DEFAULT_PORT);
					mongoClient = new MongoClient(host, Integer.parseInt(port));
					mdb = mongoClient.getDatabase(databaseName);
				} else if (MODE_2.equals(mode)) {
					String replSetHost = mongodbProp.getProperty("replSetHost");
					String[] addresses = replSetHost.split(";");
					List<ServerAddress> sas = new ArrayList<>();
					for (String address : addresses) {
						String[] splits = address.split(":");
						ServerAddress sa = new ServerAddress(splits[0], Integer.parseInt(splits[1]));
						sas.add(sa);
					}
					mongoClient = new MongoClient(sas);
					mdb = mongoClient.getDatabase(databaseName);
				}

			} catch (Exception e) {
				throw new RuntimeException(e.getMessage(), e);
			}
		}
	}

	public static MongodbManager getInstance() {
		if (instance == null) {
			instance = new MongodbManager();
		}
		return instance;
	}

	private static MongoClient mongoClient = null;

	private static MongoDatabase mdb = null;

	public static MongoClient getMongoClient() {
		return mongoClient;
	}

	public static MongoDatabase getMongoDatabase(String databaseName) {
		return getMongoClient().getDatabase(databaseName);
	}

	public static MongoDatabase getMongoDatabase() {
		return mdb;
	}

	public static MongoCollection getMongoCollection(String collectionName) {
		return getMongoDatabase().getCollection(collectionName);
	}

	public static void shutdown() {
		if (mongoClient != null) {
			mongoClient.close();
		}
	}
}
